package com.jcbase.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jcbase.core.BaseConstance;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.FileUtils;
import com.jcbase.core.util.UUIDHexgenerator;
import com.jcbase.core.weixin.template.DataItem;
import com.jcbase.core.weixin.template.TempToJson;
import com.jcbase.model.RisebdMember;
import com.jcbase.model.RisebdWechatReply;
import com.jfinal.kit.JsonKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.api.MediaApi.MediaType;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.api.UserApi;

/**
 * @category 完成业务处理服务
 * 
 * @author yiz
 * @date 2016年8月10日 下午4:35:23
 * @version 1.0.0 
 * @copyright 
 */
public class CompleteService {
	private static final Logger logger = LoggerFactory.getLogger(CompleteService.class);

	/**
	 * @category 发送优惠券微信消息
	 * @param openid
	 * @param templateId
	 * @param topColor
	 * @param jumpUrl
	 * @param dataItem
	 */
	public static void sendTemplate(String openid, String templateId, String topColor, String jumpUrl,
			DataItem dataItem) {
		String json = TempToJson.getTempJson(openid, templateId, topColor, jumpUrl, dataItem);
		ApiResult result = TemplateMsgApi.send(json);
		logger.info("发送给openid={},的优惠券的信息result = {}", openid, result.getJson());
	}

	/**
	 * @category 更新关注状态
	 * @param openid
	 */
	public static void updateSubscribe(String openid) {
		RisebdMember.me.updateSubscribe(openid, 0);
	}

	/**
	 * @category 关注时
	 * @param openid
	 */
	public static void followerSubscribe(String openid) {
		boolean exist = RisebdMember.me.existMember(openid);
		if (!exist) {
			ApiResult userInfo = UserApi.getUserInfo(openid);
			//是否关注
			int subscribe = 0;
			if (userInfo.isSucceed()) {
				JSONObject jsonObject = JSON.parseObject(userInfo.getJson());
				String nickName = jsonObject.getString("nickname");
				int sex = jsonObject.getIntValue("sex");
				String city = jsonObject.getString("city");//城市
				String province = jsonObject.getString("province");//省份
				String country = jsonObject.getString("country");//国家
				String headimgurl = jsonObject.getString("headimgurl");
				subscribe = jsonObject.getIntValue("subscribe");
				logger.info("保存会员信息userInfo={}", JsonKit.toJson(userInfo));
				//保存关注着会员的信息
				RisebdMember.me.saveMember(null, openid, nickName, null, null, sex, country, province, city, subscribe,
						headimgurl, 0);
			}
		} else {
			RisebdMember.me.updateSubscribe(openid, 1);
		}
	}

	public static void sendMsg(String openid, RisebdWechatReply risebdWechatReply) {
		Integer msgType = risebdWechatReply.getMsgType();
		if (msgType == 1) {
			CustomServiceApi.sendText(openid, risebdWechatReply.getContent());
		} else if (msgType == 2) {
			String media_id = risebdWechatReply.getMediaId();
			if (CommonUtils.isEmpty(media_id)) {
				ApiResult apiResult = null;
				File file = null;
				try {
					String mainImg = risebdWechatReply.getMainImg();
					String fileName = null;
					if (CommonUtils.isNotEmpty(mainImg)) {
						int index = mainImg.lastIndexOf("/");
						fileName = mainImg.substring(index + 1, mainImg.length());
					} else {
						fileName = UUIDHexgenerator.generate() + ".png";
					}
					file = FileUtils.createFileByUrl(BaseConstance.STATIC_URL + mainImg, fileName);
					apiResult = MediaApi.uploadMedia(MediaType.IMAGE, file);
				} catch (IOException e) {
					logger.info("图片获取失败e={}");
				} finally {
					if (file != null) {
						FileUtils.deleteFile(file);
					}
				}
				String json = apiResult.getJson();
				JSONObject jsonObject = JSON.parseObject(json);
				media_id = jsonObject.getString("media_id");
			}
			if (CommonUtils.isNotEmpty(media_id)) {
				CustomServiceApi.sendImage(openid, media_id);
			}
		} else if (msgType == 3) {
			List<Articles> articles = new ArrayList<Articles>();
			Articles article = new Articles();
			article.setDescription(risebdWechatReply.getContent());
			article.setPicurl(BaseConstance.STATIC_URL + risebdWechatReply.getMainImg());
			article.setTitle(risebdWechatReply.getTitle());
			article.setUrl(risebdWechatReply.getUrl());
			articles.add(article);
			CustomServiceApi.sendNews(openid, articles);
		}
	}

}
